#include "simplechartwidget.h"
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QLinearGradient>
#include <QtMath>
#include <QDebug>
#include <QPainterPath>

SimpleChartWidget::SimpleChartWidget(const QString &title, QWidget *parent)
    : QWidget(parent), m_title(title), m_chartColor(QColor(33, 150, 243)) // 蓝色
      ,
      m_margins(60, 40, 30, 80) // 左、上、右、下边距 - 增加边距给标签更多空间
      ,
      m_pointRadius(4), m_axisTickLength(5), m_gridSpacing(20), m_isInitialized(false)
{
    // 设置字体 - 增大字体尺寸
    m_titleFont = font();
    m_titleFont.setPointSize(14); // 从12改为14
    m_titleFont.setBold(true);

    m_labelFont = font();
    m_labelFont.setPointSize(10); // 从9改为10

    // 设置最小尺寸 - 增加尺寸
    setMinimumSize(350, 250); // 从(250, 200)增加到(350, 250)

    // 设置背景
    setStyleSheet("SimpleChartWidget { background-color: white; border: 1px solid #ddd; }");

    // 标记为已初始化
    m_isInitialized = true;
}

void SimpleChartWidget::setChartData(const QList<QPair<QString, int>> &data)
{
    m_data = data;
    update(); // 触发重绘
}

void SimpleChartWidget::setChartTitle(const QString &title)
{
    m_title = title;
    update();
}

void SimpleChartWidget::setChartColor(const QColor &color)
{
    m_chartColor = color;
    update();
}

void SimpleChartWidget::clearData()
{
    m_data.clear();
    update();
}

QSize SimpleChartWidget::sizeHint() const
{
    return QSize(400, 300); // 从(300, 250)增加到(400, 300)
}

QSize SimpleChartWidget::minimumSizeHint() const
{
    return QSize(200, 150);
}

void SimpleChartWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    // 检查初始化状态和窗口有效性
    if (!m_isInitialized || !isVisible() || width() <= 0 || height() <= 0)
    {
        return;
    }

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    // 绘制背景
    painter.fillRect(rect(), QColor(255, 255, 255));

    // 绘制标题
    if (!m_title.isEmpty())
    {
        drawTitle(painter, rect());
    }

    // 如果没有数据，显示提示信息
    if (m_data.isEmpty())
    {
        painter.setPen(QColor(120, 120, 120));
        painter.setFont(m_labelFont);
        QRect textRect = rect().adjusted(20, 20, -20, -20);
        painter.drawText(textRect, Qt::AlignCenter,
                         "暂无数据\n\n点击刷新按钮获取最新数据");
        return;
    }

    // 计算绘图区域
    QRect plotArea = calculatePlotArea(rect());

    // 绘制坐标轴
    drawAxes(painter, plotArea);

    // 绘制数据
    drawData(painter, plotArea);
}

void SimpleChartWidget::drawTitle(QPainter &painter, const QRect &rect)
{
    // 增大标题字体和间距
    painter.setFont(m_titleFont);
    painter.setPen(QColor(40, 40, 40)); // 更深的颜色

    QFontMetrics fm(m_titleFont);
    int titleHeight = fm.height();
    QRect titleRect(rect.left(), rect.top() + 8, rect.width(), titleHeight + 4);
    painter.drawText(titleRect, Qt::AlignCenter, m_title);

    // 在标题下方添加分隔线
    painter.setPen(QPen(QColor(200, 200, 200), 1));
    int lineY = titleRect.bottom() + 3;
    int lineMargin = rect.width() * 0.2;
    painter.drawLine(rect.left() + lineMargin, lineY,
                     rect.right() - lineMargin, lineY);
}

QRect SimpleChartWidget::calculatePlotArea(const QRect &widgetRect)
{
    int titleHeight = 0;
    if (!m_title.isEmpty())
    {
        QFontMetrics fm(m_titleFont);
        titleHeight = fm.height() + 20; // 增加间距为标题和分隔线留出空间
    }

    int plotWidth = widgetRect.width() - m_margins.left() - m_margins.right();
    int plotHeight = widgetRect.height() - m_margins.top() - m_margins.bottom() - titleHeight;

    // 确保绘图区域有最小尺寸
    plotWidth = qMax(50, plotWidth);
    plotHeight = qMax(50, plotHeight);

    return QRect(
        widgetRect.left() + m_margins.left(),
        widgetRect.top() + m_margins.top() + titleHeight,
        plotWidth,
        plotHeight);
}

QPair<int, int> SimpleChartWidget::getDataRange()
{
    if (m_data.isEmpty())
    {
        return qMakePair(0, 100);
    }

    int minValue = m_data.first().second;
    int maxValue = m_data.first().second;

    for (const auto &item : m_data)
    {
        minValue = qMin(minValue, item.second);
        maxValue = qMax(maxValue, item.second);
    }

    // 添加一些边距使图表更美观
    int range = maxValue - minValue;
    if (range <= 0)
    {
        if (minValue < 0)
        {
            minValue = minValue - 1;
            maxValue = 1;
        }
        else
        {
            minValue = 0;
            maxValue = qMax(10, maxValue + 1);
        }
    }
    else
    {
        int padding = range * 0.1;
        minValue = qMax(0, minValue - padding);
        maxValue = maxValue + padding;
    }

    return qMakePair(minValue, maxValue);
}

void SimpleChartWidget::drawAxes(QPainter &painter, const QRect &plotArea)
{
    painter.setPen(QPen(QColor(150, 150, 150), 1));
    painter.setFont(m_labelFont);

    // 绘制X轴
    painter.drawLine(plotArea.bottomLeft(), plotArea.bottomRight());

    // 绘制Y轴
    painter.drawLine(plotArea.bottomLeft(), plotArea.topLeft());

    // 绘制X轴标签
    if (!m_data.isEmpty())
    {
        // 根据宽度动态计算标签数量，避免重叠
        int maxLabels = qMax(1, qMin(m_data.size(), plotArea.width() / 80));
        int step = qMax(1, m_data.size() / maxLabels);

        // 使用稍大的标签字体
        QFont labelFont = m_labelFont;
        labelFont.setPointSize(9);
        painter.setFont(labelFont);
        QFontMetrics fm(labelFont);

        for (int i = 0; i < m_data.size(); i += step)
        {
            int x = (m_data.size() > 1) ? plotArea.left() + (plotArea.width() * i) / (m_data.size() - 1) : plotArea.left() + plotArea.width() / 2;

            // 绘制刻度线
            painter.setPen(QPen(QColor(150, 150, 150), 1));
            painter.drawLine(x, plotArea.bottom(), x, plotArea.bottom() + m_axisTickLength);

            // 绘制标签（格式化日期显示）
            QString label = formatDateLabel(m_data[i].first);
            if (label.length() > 10)
            {
                label = label.left(8) + "...";
            }

            // 增大标签区域和字体
            QRect labelRect(x - 40, plotArea.bottom() + m_axisTickLength + 3, 80, fm.height());
            painter.setPen(QPen(QColor(80, 80, 80), 1));
            painter.drawText(labelRect, Qt::AlignCenter, label);
        }
    }

    // 绘制Y轴标签
    QPair<int, int> range = getDataRange();
    int minValue = range.first;
    int maxValue = range.second;

    int labelCount = 5; // Y轴显示5个标签
    painter.setFont(m_labelFont);
    for (int i = 0; i <= labelCount; i++)
    {
        int value = minValue + (maxValue - minValue) * i / labelCount;
        int y = plotArea.bottom() - (plotArea.height() * i) / labelCount;

        // 绘制刻度线
        painter.setPen(QPen(QColor(150, 150, 150), 1));
        painter.drawLine(plotArea.left() - m_axisTickLength, y, plotArea.left(), y);

        // 格式化Y轴标签数值
        QString labelText;
        if (value >= 10000)
        {
            labelText = QString::number(value / 1000.0, 'f', 1) + "k";
        }
        else if (value >= 1000)
        {
            labelText = QString::number(value / 1000.0, 'f', 1) + "k";
        }
        else
        {
            labelText = QString::number(value);
        }

        // 绘制标签 - 增大标签区域
        painter.setPen(QPen(QColor(80, 80, 80), 1));
        QRect labelRect(plotArea.left() - 55, y - 10, 50, 20);
        painter.drawText(labelRect, Qt::AlignRight | Qt::AlignVCenter, labelText);

        // 绘制网格线（更淡的颜色）
        if (i > 0 && i < labelCount)
        {
            painter.setPen(QPen(QColor(245, 245, 245), 1, Qt::DotLine));
            painter.drawLine(plotArea.left(), y, plotArea.right(), y);
        }
    }
}

void SimpleChartWidget::drawData(QPainter &painter, const QRect &plotArea)
{
    if (m_data.size() < 2)
    {
        // 如果只有一个数据点，绘制柱状图
        if (m_data.size() == 1)
        {
            QPair<int, int> range = getDataRange();
            int value = m_data.first().second;

            // 计算柱状图参数
            int barWidth = qMin(60, plotArea.width() / 4);
            int x = plotArea.left() + plotArea.width() / 2;
            int valueRange = range.second - range.first;
            if (valueRange <= 0)
                valueRange = 1;

            int barHeight = ((value - range.first) * plotArea.height()) / valueRange;
            int barTop = plotArea.bottom() - barHeight;

            // 绘制渐变柱状图
            QLinearGradient gradient(x, barTop, x, plotArea.bottom());
            gradient.setColorAt(0, m_chartColor);
            gradient.setColorAt(1, m_chartColor.lighter(150));

            QRect barRect(x - barWidth / 2, barTop, barWidth, barHeight);
            painter.fillRect(barRect, QBrush(gradient));

            // 绘制边框
            painter.setPen(QPen(m_chartColor.darker(120), 2));
            painter.drawRect(barRect);

            // 在柱状图上方显示数值
            painter.setPen(QPen(Qt::black, 1));
            painter.setFont(m_labelFont);
            QString valueText = QString::number(value);
            painter.drawText(barRect.adjusted(0, -25, 0, -5), Qt::AlignCenter, valueText);
        }
        return;
    }

    QPair<int, int> range = getDataRange();
    int minValue = range.first;
    int maxValue = range.second;
    int valueRange = maxValue - minValue;

    if (valueRange <= 0)
    {
        valueRange = 1; // 防止除零错误
    }

    // 准备绘制路径
    QList<QPoint> points;
    for (int i = 0; i < m_data.size(); ++i)
    {
        int x = plotArea.left() + (plotArea.width() * i) / (m_data.size() - 1);
        int value = m_data[i].second;
        int y = plotArea.bottom() - ((value - minValue) * plotArea.height()) / valueRange;
        points.append(QPoint(x, y));
    }

    // 绘制填充区域
    if (points.size() > 1)
    {
        QLinearGradient gradient(0, plotArea.top(), 0, plotArea.bottom());
        gradient.setColorAt(0, QColor(m_chartColor.red(), m_chartColor.green(),
                                      m_chartColor.blue(), 100));
        gradient.setColorAt(1, QColor(m_chartColor.red(), m_chartColor.green(),
                                      m_chartColor.blue(), 20));

        QPainterPath fillPath;
        fillPath.moveTo(points.first().x(), plotArea.bottom());
        fillPath.lineTo(points.first());

        for (int i = 1; i < points.size(); ++i)
        {
            fillPath.lineTo(points[i]);
        }

        fillPath.lineTo(points.last().x(), plotArea.bottom());
        fillPath.closeSubpath();

        painter.fillPath(fillPath, QBrush(gradient));
    }

    // 绘制连线
    painter.setPen(QPen(m_chartColor, 2));
    for (int i = 1; i < points.size(); ++i)
    {
        painter.drawLine(points[i - 1], points[i]);
    }

    // 绘制数据点
    painter.setBrush(QBrush(Qt::white));
    painter.setPen(QPen(m_chartColor, 2));

    for (const QPoint &point : points)
    {
        painter.drawEllipse(point.x() - m_pointRadius, point.y() - m_pointRadius,
                            m_pointRadius * 2, m_pointRadius * 2);
    }
}

void SimpleChartWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);

    // 确保在尺寸变化后安全重绘
    if (m_isInitialized && event->size().isValid() &&
        event->size().width() > 0 && event->size().height() > 0)
    {
        update();
    }
}

// 格式化日期标签，将"2024-09"格式转换为"2024年9月"
QString SimpleChartWidget::formatDateLabel(const QString &dateStr)
{
    // 检查是否是YYYY-MM格式
    QRegExp dateRegex("^(\\d{4})-(\\d{1,2})$");
    if (dateRegex.exactMatch(dateStr))
    {
        QString year = dateRegex.cap(1);
        int month = dateRegex.cap(2).toInt();
        return QString("%1年%2月").arg(year).arg(month);
    }
    
    // 如果不匹配日期格式，返回原字符串
    return dateStr;
}
